package controller;

import entity.*;
import entity.ProductDetails;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import relationEntity.*;
import service.*;
import util.Page;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by jifeng on 2016/12/12 0012.
 */
@Controller
public class ProductController {
    @Resource(name = "productService")
    private ProductService productService;
    @Resource(name = "categoryService")
    private CategoryService categoryService;
    @Resource(name="subCategoryService")
    private SubCategoryService subCategoryService;
    @Resource(name="colorSizeService")
    private ColorSizeService colorSizeService;
    @Resource(name = "productDetailsService")
    private ProductDetailsService productDetailsService;
    @Resource(name = "stockService")
    private StockService stockService;
    @Resource(name = "userService")
    private UserService userService;

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    public void addProduct(Product product){
        getCurrentSession().save(product);
    }
    /**
    * Created by jifeng
    * 添加类别
    * */
    @RequestMapping(value = "/addCategory")
    public String  addCategory(HttpServletRequest request,HttpServletResponse response){
        Category category = new Category();
        SubCategory subCategory = new SubCategory();
        ColorSize colorSize = new ColorSize();
        int cate = Integer.valueOf(request.getParameter("cate"));
        String superior = request.getParameter("superior");
        String classificationName = request.getParameter("classificationName");
        if (cate ==1){
            category.setCategoryName(classificationName);
            categoryService.addCategory(category);
        }
        if (cate==2){
            subCategory.setSubCategoryName(classificationName);
            subCategoryService.addSubCategory(subCategory,Integer.valueOf(superior));
        }
        if (cate==3){
            colorSize.setColorSizeName(classificationName);
            colorSizeService.addColorSize(colorSize,Integer.valueOf(superior));
        }
        return "redirect:/classifyList";
    }

   /* *//**
     * Created by jifeng
     * 添加二级类
     * *//*
    @RequestMapping(value = "/addSubCategory")
    public String  addSubCategory(String name){
        SubCategory subCategory = new SubCategory();
        subCategory.setSubCategoryName(name);
        subCategoryService.addSubCategory(subCategory);
        return "redirect:/classifyList";
    }

    *//**
     * Created by jifeng
     * 添加三级类
     * *//*
    public String addColorSize(String name){
        ColorSize colorSize = new ColorSize();
        colorSize.setColorSizeName(name);
        colorSizeService.addColorSize(colorSize);
        return "redirect:/classifyList";
    }*/

    /**
     * Created by jifeng
     * 查询商品类别列表
     * */
    @ResponseBody
    @RequestMapping(value = "/classifyList")
    public ModelAndView classifyList(HttpServletRequest request,HttpServletResponse response){
        ModelAndView mv = new ModelAndView();
        String cate = request.getParameter("category");
        /*String superior = request.getParameter("superior");*/
        if (cate==null){
            cate="0";
        }
        List list = new ArrayList();
        if (Integer.valueOf(cate)==1){
            list=null;
        }
        if (Integer.valueOf(cate)==2){
            list=categoryService.findCategoryList();
        }
        if(Integer.valueOf(cate)==3){
            list=subCategoryService.findSubCategoryList();
        }
        List<Category> categoryList =categoryService.findCategoryList();
        List<SubCategory> subCategoryList =null;
        List<ColorSize> colorSizeList=null;
        for (Category category:categoryList){
                subCategoryList=subCategoryService.findSubCategoryListById(category.getId());
                category.setSubCategories(new HashSet(subCategoryList));
                for (SubCategory subCategory:subCategoryList){
                    colorSizeList=colorSizeService.findColorSizeListById(subCategory.getId());
                    subCategory.setColorSizes(new HashSet<ColorSize>(colorSizeList));
                }
        }
        mv.addObject("categoryList",categoryList);
        mv.addObject("category",cate);
        mv.setViewName("classifyList");
        mv.addObject("list",list);
        return mv;
    }

    /**
     * Created by jifeng
     * 查询商品列表
     * */
    @ResponseBody
    @RequestMapping(value = "/productList")
    public Model productList(HttpServletRequest request, HttpServletResponse response, Model mv){
        try {
            String userName=String.valueOf(request.getSession().getAttribute("userName"));
            String pageNo = request.getParameter("pageNo");
            String categoryName = request.getParameter("categoryName");
            String subCategoryName = request.getParameter("subCategoryName");
            String colorSizeName = request.getParameter("colorSizeName");
            String sell = request.getParameter("sell");
            String productName =request.getParameter("productName");
            if (pageNo == null) {
                pageNo = "1";
            }
            Page page =productService.findProductList(Integer.valueOf(pageNo),categoryName,subCategoryName,colorSizeName,sell,productName, 10);
            mv.addAttribute("page",page);
            List<Products> productList = page.getList();
            List<Category> categoryList = categoryService.findCategoryList();
            List<SubCategory> subCategoryList = subCategoryService.findSubCategoryList();
            List<ColorSize> colorSizeList = colorSizeService.findColorSizeList();
            mv.addAttribute("categoryName",categoryName);
            mv.addAttribute("subCategoryName",subCategoryName);
            mv.addAttribute("colorSizeName",colorSizeName);
            mv.addAttribute("sell",sell);
            mv.addAttribute("productName",productName);
            /*mv.addAttribute("categoryList",categoryList);
            mv.addAttribute("subCategoryList",subCategoryList);*/
            mv.addAttribute("colorSizeList",colorSizeList);
            mv.addAttribute("productList",productList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }

    /**
     * Created by jifeng
     * 批量删除商品，伪删除，只是改变delete状态为1
     * */
    @RequestMapping(value = "/deleteProduct")
    public String deleteProduct(String ids){
        if (ids!=null&&ids!="") {
            productService.deleteProduct(ids);
        }
        return "redirect:/productList";
    }

    /**
     * Created by jifeng
     * 批量恢复删除商品，改变delete状态为0
     * */
    @RequestMapping(value = "/recoveryProduct")
    public  String recoveryProduct(String ids){
        if (ids!=null&&ids!="") {
            productService.recoveryProduct(ids);
        }
        return "redirect:/productList";
    }

    /**
     * Created by jifeng
     * 回收站列表，存放所有delete为1的商品
     * */
    @RequestMapping(value = "/recycleBin")
    public Model recycleBin(HttpServletRequest request, HttpServletResponse response, Model mv){
        try {
            String pageNo = request.getParameter("pageNo");
            if (pageNo == null) {
                pageNo = "1";
            }
            String categoryName = request.getParameter("categoryName");
            String subCategoryName = request.getParameter("subCategoryName");
            String colorSizeName = request.getParameter("colorSizeName");
            String productName =request.getParameter("productName");
            Page page =productService.recycleProductList(Integer.valueOf(pageNo),categoryName,subCategoryName,colorSizeName,productName, 10);
            mv.addAttribute("page",page);
            List<Products> productList = page.getList();
            List<Category> categoryList = categoryService.findCategoryList();
            List<SubCategory> subCategoryList = subCategoryService.findSubCategoryList();
            List<ColorSize> colorSizeList = colorSizeService.findColorSizeList();
            mv.addAttribute("categoryName",categoryName);
            mv.addAttribute("subCategoryName",subCategoryName);
            mv.addAttribute("colorSizeName",colorSizeName);
            mv.addAttribute("productName",productName);
            mv.addAttribute("categoryList",categoryList);
            mv.addAttribute("subCategoryList",subCategoryList);
            mv.addAttribute("colorSizeList",colorSizeList);
            mv.addAttribute("productList",productList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }

    /**
     * Created by jifeng
     * 批量上架商品，把sell的状态改为1
     * */
    @RequestMapping(value = "/sellProduct")
    public  String sellProduct(String ids1){
        if (ids1!=null&&ids1!="") {
            productService.sellProduct(ids1);
        }
        return "redirect:/productList";
    }

    /**
     * Created by jifeng
     * 批量下架商品，把sell的状态改为0
     * */
    @RequestMapping(value = "/noSellProduct")
    public  String noSellProduct(String ids2){
        if (ids2!=null&&ids2!="") {
            productService.noSellProduct(ids2);
        }
        return "redirect:/productList";
    }

   /* @RequestMapping(value="/json")
    public @ResponseBody List<Products> getShopInJSON(HttpServletRequest request,HttpServletResponse response) {
        String pageNo = request.getParameter("pageNo");
        Page page =productService.recycleProductList(Integer.valueOf(pageNo), 1);
        List<Products> productList = page.getList();
        *//*List<Map<String, Object>> datas = MetaOper.read("SELECT p.name as productName,p.nowPrice,p.sell,c.name as categoryName,si.name AS colorSizeName,s.stocks FROM Product AS p ,Stock AS s,Category AS c ,ColorSize as si where p.delete=0");*//*

        return productList;

    }*/

    /**
     * Created by jifeng
     * 类别选择
     * *//*
    @RequestMapping(value = "/categorySelect")
    public String categorySelect(HttpServletRequest request,HttpServletResponse response){
        String categoryId = request.getParameter("categoryId");
        String subCategoryId = request.getParameter("subCategoryId");
        return "redirect:/toAddProduct?categoryId=" + categoryId + "&subCategoryId="+subCategoryId+"";
    }
*/

    /**
     * Created by jifeng
     * 商品添加跳转
     * */
    @RequestMapping(value = "/toAddProduct")
    public ModelAndView toAddProduct(HttpServletRequest request,HttpServletResponse response){
        ModelAndView mv = new ModelAndView();
        List<SubCategory> subCategoryList =null;
        List<ColorSize> colorSizeList =null;
        String categoryId = request.getParameter("categoryId");
        String subCategoryId = request.getParameter("subCategoryId");
        List<Category> categoryList = categoryService.findCategoryList();
        if (categoryId !=null) {
            int cId = Integer.valueOf(categoryId);
            subCategoryList = subCategoryService.findSubCategoryListById(cId);
        }
        if (subCategoryId!=null && subCategoryId!=""){
            int sId = Integer.valueOf(subCategoryId);
            colorSizeList=colorSizeService.findColorSizeListById(sId);
        }
        mv.addObject("categoryList",categoryList);
        mv.addObject("subCategoryList",subCategoryList);
        mv.addObject("colorSizeList",colorSizeList);
        mv.addObject("subCategoryId",subCategoryId);
        mv.addObject("categoryId",categoryId);
        mv.setViewName("addProduct");
        return mv;
    }



    /**
     * Created by jifeng
     * 商品添加
     * */
    @RequestMapping(value = "/addProduct")
    public String addProduct(HttpServletRequest request, HttpServletResponse response,@RequestParam MultipartFile[] myfiles)throws IllegalStateException, IOException {
        List list =new ArrayList();
        for(MultipartFile myfile : myfiles){
            String fileName=myfile.getOriginalFilename();
            // 项目在容器中实际发布运行的根路径
            String realPath=request.getSession().getServletContext().getRealPath("/");
            // 自定义的文件名称
            String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
            // 设置存放图片文件的路径
            String path= realPath+trueFileName;
            String path1 =trueFileName;
            list.add(path1);
            System.out.println("存放图片文件的路径:"+path);
            myfile.transferTo(new File(path));
            System.out.println("文件成功上传到指定目录下");
        }
        String categoryId = request.getParameter("categoryId");//品类
        String subCategoryId =request.getParameter("subCategoryId");//系列
        String colorSizeId = request.getParameter("colorSizeId");//规格
        String productName = request.getParameter("productName");//产品名字
        String keyWord =request.getParameter("keyWord");//关键词
        String sell = request.getParameter("sell");//上下架
        String stocks=request.getParameter("stocks");//库存
        String basicsNum = request.getParameter("basicsNum");//销售基数
        String originalPrice = request.getParameter("originalPrice");//市场价格
        String nowPrice = request.getParameter("nowPrice");//销售价格
        String cost= request.getParameter("cost");//本金
        String brand= request.getParameter("brand");//品牌
        String productCode = request.getParameter("productCode");//货号
        String pendulumType = request.getParameter("pendulumType");//摆型
        String collarType = request.getParameter("collarType");//领型
        String color = request.getParameter("color");//颜色
        String size = request.getParameter("size");//尺寸
        String year =request.getParameter("year");//出产时期
        String style =request.getParameter("style");//风格
        String fabric=request.getParameter("fabric");//面料
        String sleeve=request.getParameter("sleeve");//袖长
        String age =request.getParameter("age");//适用年龄
        String scene=request.getParameter("scene");//适用场景
        String elements=request.getParameter("elements");//流行元素
        String technology=request.getParameter("technology");//服饰工艺
        String object= request.getParameter("object");//适用对象
        String waistType=request.getParameter("waistType");//腰型

        Product product = new Product();
        product.setBasicsNum(Long.valueOf(basicsNum));
        product.setCategory(Integer.valueOf(categoryId));
        product.setCost(Long.valueOf(cost));
        product.setKeyWord(keyWord);
        product.setNowPrice(Long.valueOf(nowPrice));
        product.setColorSizeId(Integer.valueOf(colorSizeId));
        product.setOriginalPrice(Long.valueOf(originalPrice));
        product.setProductName(productName);
        product.setSell(Integer.valueOf(sell));
        product.setSubCategory(Integer.valueOf(subCategoryId));
        product.setCarousel0(list.get(0).toString());
        product.setCarousel1(list.get(1).toString());
        product.setCarousel2(list.get(2).toString());
        product.setCarousel3(list.get(3).toString());
        product.setCarousel4(list.get(4).toString());
        product.setDetailDrawing0(list.get(5).toString());
        product.setDetailDrawing1(list.get(6).toString());
        product.setDetailDrawing2(list.get(7).toString());
        product.setDeletes(0);
        productService.addProduct(product);
        ProductDetails productDetails = new ProductDetails();
        productDetails.setBrand(brand);
        productDetails.setAge(age);
        productDetails.setCollarType(collarType);
        productDetails.setColor(color);
        productDetails.setElements(elements);
        productDetails.setFabric(fabric);
        productDetails.setObject(object);
        productDetails.setPendulumType(pendulumType);
        productDetails.setProductCode(productCode);
        productDetails.setScene(scene);
        productDetails.setSize(size);
        productDetails.setSleeve(sleeve);
        productDetails.setStyle(style);
        productDetails.setTechnology(technology);
        productDetails.setWaistType(waistType);
        productDetails.setYear(year);
        productDetails.setProductId(product.getId());
        productDetailsService.addProductDetails(productDetails);
        Stock stock = new Stock();
        stock.setStocks(Integer.valueOf(stocks));
        stock.setProductId(product.getId());
        stock.setColorSize(Integer.valueOf(colorSizeId));
        stockService.addStock(stock);
        return "redirect:/productList";
    }


    /**
     * Created by jifeng
     * 删除三级类
     * */
    @RequestMapping(value = "/deleteColorSize")
    public String deleteColorSize(HttpServletRequest request,HttpServletResponse response){
        String colorSize = request.getParameter("colorSizeId");
        if(colorSize!=null) {
            colorSizeService.deleteColorSize(Integer.valueOf(colorSize));
        }
        return "redirect:/classifyList";
    }

    /**
     * Created by jifeng
     * 删除二级类
     * */
    @RequestMapping(value = "/deleteSubCategory")
    public String deleteSubCategory(HttpServletRequest request,HttpServletResponse response){
        String subCategoryId = request.getParameter("subCategoryId");
        List<ColorSize> colorSizeList = colorSizeService.findColorSizeListById(Integer.valueOf(subCategoryId));
        for (ColorSize colorSize:colorSizeList){
            colorSizeService.deleteColorSize(colorSize.getId());
        }
        subCategoryService.deleteSubCategory(Integer.valueOf(subCategoryId));
        return "redirect:/classifyList";
    }


    /**
     * Created by jifeng
     * 删除一级类
     * */
    @RequestMapping(value = "/deleteCategory")
    public String deleteCategory(HttpServletRequest request,HttpServletResponse response){
        String categoryId = request.getParameter("categoryId");
        List<SubCategory> subCategoryList =subCategoryService.findSubCategoryListById(Integer.valueOf(categoryId));
        for (SubCategory subCategory:subCategoryList){
            List<ColorSize> colorSizeList = colorSizeService.findColorSizeListById(subCategory.getId());
            for (ColorSize colorSize:colorSizeList){
                colorSizeService.deleteColorSize(colorSize.getId());
            }
            subCategoryService.deleteSubCategory(subCategory.getId());
        }
        categoryService.deleteCategory(Integer.valueOf(categoryId));
        return "redirect:/classifyList";
    }



    /**
     * Created by jifeng
     * 编辑三级类
     * */
    @RequestMapping(value = "/updateColorSize")
    public String updateColorSize(HttpServletRequest request,HttpServletResponse response){
        String colorSizeIds=request.getParameter("colorSizeIds");
        String colorName = request.getParameter("colorNames");
        colorSizeService.updateColorS(Integer.valueOf(colorSizeIds),colorName);
        return "redirect:/classifyList";
    }

    /**
     * Created by jifeng
     * 编辑二级类
     * */
    @RequestMapping(value = "/updateSubCategory")
    public String updateSubCategory(HttpServletRequest request,HttpServletResponse response){
        String subIds=request.getParameter("subIds");
        String subNames = request.getParameter("subNames");
        subCategoryService.updateSub(Integer.valueOf(subIds),subNames);
        return "redirect:/classifyList";
    }

    /**
     * Created by jifeng
     * 编辑一级类
     * */
    @RequestMapping(value = "/updateCategory")
    public String updateCategory(HttpServletRequest request,HttpServletResponse response){
        String catIds=request.getParameter("catIds");
        String catNames = request.getParameter("catNames");
        categoryService.updateCate(Integer.valueOf(catIds),catNames);
        return "redirect:/classifyList";
    }
    /**
     * Created by jifeng
     * 查看商品详情
     * */
    @RequestMapping(value = "/toProductDetails")
    public ModelAndView toProductDetails(HttpServletRequest request,HttpServletResponse response,ModelAndView mv){
        String productId = request.getParameter("productId");
        List<ProductsDetails> productsDetailsList = productService.displayProductDetails(Integer.valueOf(productId));
        mv.addObject("ProductsDetails", productsDetailsList.get(0));
        mv.setViewName("goodsDetails");
        return mv;
    }



    /**
     * Created by jifeng
     * 跳转商品修改
     * */
    @RequestMapping(value = "/toUpdateProductDetails")
    public ModelAndView toUpdateProductDetails(HttpServletRequest request,HttpServletResponse response,ModelAndView mv){
        String productId = request.getParameter("pId");
        List<ProductsDetails> productsDetailsList = productService.displayProductDetails(Integer.valueOf(productId));
        mv.addObject("ProductsDetails", productsDetailsList.get(0));
        mv.setViewName("goodsEdit");
        return mv;
    }

    /**
     * Created by jifeng
     * 商品修改
     * */
    @RequestMapping(value = "/updateProductDetails")
    public String updateProductDetails(HttpServletRequest request,HttpServletResponse response,@RequestParam MultipartFile[] myfiles)throws IllegalStateException, IOException{
        String pId=request.getParameter("pId");
        List list =new ArrayList();
        for(MultipartFile myfile : myfiles){
            String fileName=myfile.getOriginalFilename();
            String realPath=request.getSession().getServletContext().getRealPath("/");
            String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
            String path= realPath+trueFileName;
            String path1 =trueFileName;
            list.add(path1);
            myfile.transferTo(new File(path));
        }
        String productName = request.getParameter("productName");//产品名字
        String keyWord =request.getParameter("keyWord");//关键词
        String stocks=request.getParameter("stocks");//库存
        String basicsNum = request.getParameter("basicsNum");//销售基数
        String originalPrice = request.getParameter("originalPrice");//市场价格
        String nowPrice = request.getParameter("nowPrice");//销售价格
        String cost= request.getParameter("cost");//本金
        String brand= request.getParameter("brand");//品牌
        String productCode = request.getParameter("productCode");//货号
        String pendulumType = request.getParameter("pendulumType");//摆型
        String collarType = request.getParameter("collarType");//领型
        String color = request.getParameter("color");//颜色
        String size = request.getParameter("size");//尺寸
        String year =request.getParameter("year");//出产时期
        String style =request.getParameter("style");//风格
        String fabric=request.getParameter("fabric");//面料
        String sleeve=request.getParameter("sleeve");//袖长
        String age =request.getParameter("age");//适用年龄
        String scene=request.getParameter("scene");//适用场景
        String elements=request.getParameter("elements");//流行元素
        String technology=request.getParameter("technology");//服饰工艺
        String object= request.getParameter("object");//适用对象
        String waistType=request.getParameter("waistType");//腰型
        Product product = productService.findProductById(Integer.valueOf(pId));
        product.setProductName(productName);
        product.setKeyWord(keyWord);
        product.setBasicsNum(Long.valueOf(basicsNum));
        product.setOriginalPrice(Long.valueOf(originalPrice));
        product.setNowPrice(Long.valueOf(nowPrice));
        product.setCost(Long.valueOf(cost));
        product.setCarousel0(list.get(0).toString());
        product.setCarousel1(list.get(1).toString());
        product.setCarousel2(list.get(2).toString());
        product.setCarousel3(list.get(3).toString());
        product.setCarousel4(list.get(4).toString());
        product.setDetailDrawing0(list.get(5).toString());
        product.setDetailDrawing0(list.get(6).toString());
        product.setDetailDrawing0(list.get(7).toString());
        productService.updateProduct(product);
        Stock stock = stockService.findProductById(Integer.valueOf(pId));
        stock.setStocks(Integer.valueOf(stocks));
        stockService.updateStock(stock);
        ProductDetails productDetails = productDetailsService.findProductDetailsById(Integer.valueOf(pId));
        productDetails.setBrand(brand);
        productDetails.setProductCode(productCode);
        productDetails.setPendulumType(pendulumType);
        productDetails.setYear(year);
        productDetails.setObject(object);
        productDetails.setWaistType(waistType);
        productDetails.setTechnology(technology);
        productDetails.setStyle(style);
        productDetails.setSleeve(sleeve);
        productDetails.setCollarType(collarType);
        productDetails.setColor(color);
        productDetails.setFabric(fabric);
        productDetails.setElements(elements);
        productDetails.setSize(size);
        productDetails.setAge(age);
        productDetails.setScene(scene);
        productDetailsService.updateProductDetails(productDetails);
        return "redirect:/toProductDetails?productId="+pId+"";
    }


}
